package name.zxw.rabbitmq.helloworld;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消费者
 * @author ZhangXinWang
 * @date 2022/5/18 0:16
 */
public class Consumer {
    public static final String QUEUE_NAME = "hello";

    public static void main(String[] args) {
        try {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("127.0.0.1");
            factory.setUsername("guest");
            factory.setPassword("guest");
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();
            /**
             * 消费者消费消息
             * 1. 消费那个队列
             * 2. 消费成功之后是否要自动应答,true 自动应答,false 手动应答
             * 3. 消费者未成功消费的回调
             * 4. 消费者取消消费的回调
             */
            System.out.println("C1等待接收消息...");
            channel.basicConsume(QUEUE_NAME, true,
                    (consumerTag, message) -> {
                        System.out.println("message = " + new String(message.getBody()));
                    }, (consumerTag, message) -> {
                        System.out.println("消息消费被中断");
                    });
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TimeoutException e) {
            throw new RuntimeException(e);
        }
    }


}
